package gis

import (
	"fmt"
	"math"
)

type BLPoint struct {
	B float64
	L float64
}

type BLHPoint struct {
	B float64
	L float64
	H float64
}

/*
*

	某一个纬度上 1KM,  多少秒
*/
func GetLSecondByKM(latD float64, km float64) float64 {
	// 1度= N(KM)
	l_1d_km := CalcuPerM(latD) / 1000
	return math.Floor(km / l_1d_km * 3600)
}

/*
*

	N km 需要多少纬度
*/
func GetBSecondByKM(km float64) float64 {
	return math.Floor(km * _LAT_1KM * 3600)
}

/*
*

	获取左下角的格网中心点, 单位:秒
*/
func GetLeftBottomGridS(b, l float64, bw, lw float64) (gridb, gridl float64) {
	// 求左下角的点
	gridb = float64(int(b/bw)) * bw
	gridl = float64(int(l/lw)) * lw
	return
}

/*
*

	b, l 单位：d
*/
func GetLeftBottomGrid(b, l float64, bsecs, lsecs float64) (gridb, gridl float64) {
	gridb, gridl = GetLeftBottomGridS(b*3600, l*3600, bsecs, lsecs)
	return gridb / 3600, gridl / 3600
}

/*
*
// 20度, 1KM需要秒数 取整
lsecs := gis.GetLSecondByKM(20, 60)
bsecs := gis.GetBSecondByKM(60)
*/
func FindNearest4Grid(b, l, bsecs, lsecs float64) (top0, top1, floor0, floor1 BLPoint) {
	b0, l0 := GetLeftBottomGridS(b*3600, l*3600, bsecs, lsecs)
	floor0.B, floor0.L = b0/3600, l0/3600
	floor1.B, floor1.L = b0/3600, (l0+lsecs)/3600
	top0.B, top0.L = (b0+bsecs)/3600, l0/3600
	top1.B, top1.L = (b0+bsecs)/3600, (l0+lsecs)/3600
	return
}

func FindNearest4GridEx(b, l, bsecs, lsecs float64) (rval [4]BLPoint) {
	rval[0], rval[1], rval[2], rval[3] = FindNearest4Grid(b, l, bsecs, lsecs)
	return
}

func GetNearestGridS(b, l float64, bw, lw float64) (gridb, gridl float64) {
	gridb, gridl = GetLeftBottomGridS(b, l, bw, lw)
	// 更靠近下一个
	if (b - gridb) > bw/2 {
		gridb += bw
	}
	if (l - gridl) > lw/2 {
		gridl += lw
	}
	return
}

func GetNextBGridS(gridb0, gridl0 float64, bw float64) (gridb, gridl float64) {
	return gridb0 + bw, gridl0
}

func GetNextLGridS(gridb0, gridl0 float64, lw float64) (gridb, gridl float64) {
	return gridb0, gridl0 + lw
}

// 格网 精度大约 11M
func GetNearestGridStr(b, l float64, gridlkm float64, sep string) string {
	b, l = GetNearestGrid(b, l, gridlkm)
	return fmt.Sprintf("%.4f%s%.4f", l, sep, b)
}

func GetNearestGrid(b, l float64, gridlkm float64) (gridb, gridl float64) {

	b = b * 3600
	l = l * 3600
	// 求左下角的lat(y)
	bw := GetBSecondByKM(gridlkm)
	gridb = float64(int(b/bw)) * bw
	// 靠近的lat(y)
	if (b - gridb) > bw/2 {
		gridb += bw
	}

	// 转成度
	gridb = gridb / 3600

	// 左下角的lng(x)
	lw := GetLSecondByKM(gridb, gridlkm)
	gridl = float64(int(l/lw)) * lw
	if (l - gridl) > lw/2 {
		gridl += lw
	}

	return gridb, gridl / 3600
}

func GetNextLGrid(gridb0, gridl0 float64, gridlkm float64) (gridb, gridl float64) {
	// 1度= N(KM)
	l_1d_km := CalcuPerM(gridb0) / 1000
	//l_1d_km := 111.00 * math.Cos(D2R(gridb)) // 1
	// N(km)需要多少秒
	lw := math.Floor(gridlkm / l_1d_km * 3600)

	gridb, gridl = GetNextLGridS(gridb0*3600, gridl0*3600, lw)
	return gridb / 3600, gridl / 3600
}
